package com.qk.management.service;

import com.qk.common.Result;
import com.qk.entity.Avatar;
import com.qk.management.mapper.AvatarMapper;
import com.qk.management.service.validator.FileSizeValidator;
import com.qk.management.service.validator.FileTypeValidator;
import com.qk.common.constants.AvatarMessageConstants;
import com.qk.management.service.validator.FileValidationHandler;
import com.qk.management.service.validator.ValidationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
@Slf4j
public class AvatarService {

    @Autowired
    private FileStorageService fileStorageService;

    @Autowired
    private AvatarMapper avatarMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    public Result saveAvatar(MultipartFile file, Long userId, String fileMd5) {
        try {
            validateFile(file);
            String newFilePath = fileStorageService.storeFile(file);
            Avatar newAvatar = Avatar.builder()
                    .userId(userId)
                    .filePath(newFilePath)
                    .fileMd5(fileMd5)
                    .isGarbage(0) // ACTIVE状态
                    .build();
            avatarMapper.insert(newAvatar);
            List<Avatar> historyAvatars = avatarMapper.listByUserId(userId, 3);
            if (historyAvatars.size() > 2) {
                List<Long> garbageIds = historyAvatars.stream()
                    .skip(2)
                    .map(Avatar::getId)
                    .collect(Collectors.toList());
                avatarMapper.markAsGarbage(garbageIds, 1); // GARBAGE状态
            }
            return Result.success(newAvatar);
        } catch (ValidationException e) {
            log.warn("{}: {}", AvatarMessageConstants.FILE_VALIDATION_FAILED, e.getMessage());
            return Result.error(AvatarMessageConstants.FILE_VALIDATION_FAILED + ": " + e.getMessage());
        } catch (Exception e) {
            log.error("Failed to save avatar for user: {}", userId, e);
            return Result.error(AvatarMessageConstants.AVATAR_SAVE_FAILED + ": " + e.getMessage());
        }
    }
    public Avatar getCurrentAvatar(Long userId) {
        return avatarMapper.getCurrentAvatar(userId, 0); // ACTIVE状态
    }
    private void validateFile(MultipartFile file) throws ValidationException {
        // 创建验证链
        FileValidationHandler sizeValidator = new FileSizeValidator(10 * 1024 * 1024); // 10MB限制
        FileValidationHandler typeValidator = new FileTypeValidator(getAllowedTypes());
        
        sizeValidator.setNext(typeValidator);
        sizeValidator.validate(file);
    }
    private Set<String> getAllowedTypes() {
        Set<String> allowedTypes = new HashSet<>();
        allowedTypes.add(AvatarMessageConstants.MIME_TYPE_JPEG);
        allowedTypes.add(AvatarMessageConstants.MIME_TYPE_PNG);
        allowedTypes.add(AvatarMessageConstants.MIME_TYPE_GIF);
        return allowedTypes;
    }
}